<?php 
include("header.inc.php");
include 'auth.inc.php';
?>
<h1>Edit Templates</h1>


<?php

function validateName($name) {
 if (preg_match("/^[a-zA-Z0-9_\-\.]*$/", $name))
		return true;
 else return false;

}

//echo var_dump($_POST);

$templates_path="/home/ubuntu/drd/its-a-profs-life/templates/";


/* Get templates currently availiable from file ID and create a hash
    table where the file ID map to the file names */
$output = shell_exec('ls -i1 "' . $templates_path . '"');
$plain = preg_split("/[\n]+/", $output, -1, PREG_SPLIT_NO_EMPTY);
foreach ($plain as &$value){
	$value = trim($value);
	$files[substr($value, 0, strpos($value, " "))] = substr(strstr($value," "),1);

}

/*echo var_dump($files);
echo "<hr />";
echo var_dump($plain);
echo "<hr />";
*/

/* Get Values from POST for Edit */
if ($_POST['DeleteSelected']!='Delete Selected' && 
	$_POST['Selected']=='' &&
	$_POST['Submit']=='' &&
	$_POST['Switch']=='' &&
	$_POST['Gen']=='' &&
	count($_POST)!=0) {
echo "<p>Editng File...</p>";
while (list($key, $value) = each($_POST)) {
        if (substr($key, 0, 5)=='edit_' && $value == 'Edit') {
                $edit_selected = $files[substr($key, 5)];
		$target = $templates_path . $edit_selected;
        } else if (substr($key, 0, 7)=='delete_') {
                continue;
        } else {
                break;
        }
}
}


/* Get type of input based on input switch */
if ($edit_selected!='' || $_POST['Switch']=='Form Input') {
	$_GET['input'] = '';
} else if ($_POST['Switch']=='File Input') {
	$_GET['input'] = 'file';
} 



/* ADD FILE from FILE INPUT */
//http://www.tizag.com/phpT/fileupload.php
if ($_POST['Submit']=='Upload File') {
echo "<p>Adding...";
if ($_POST['templateName']=='') {
	$_POST['templateName'] = $_FILES['uploadedFile']['name'];
}
if (!validateName($_POST['templateName'])) {
	echo "</p><p class=\"error-message\">Error: File name contains at least 1 illegal character";
	$error_exists = true;
} else if (!in_array($_POST['templateName'], $files)) {
	$target_path = $templates_path . $_POST['templateName'];
	if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'], $target_path)) {
		echo "...Done</p>";
	} else {
		echo "</p><p class=\"error-message\">Error: There was an error uploading the file; please try again.</p>";
		$error_exists = true;
	}
} else {
	echo "</p><p class=\"error-message\">Error: Unable to add file (\"" . $_POST['templateName'] . "\"); file already exists</p>";
	$error_exists = true;
}

}

/* SWITCH from FILE INPUT */
if ($_POST['Switch']=='Form Input' && $_FILES['uploadedFile']['name']!='') {
if ($_POST['templateName']=='') {
	$_POST['templateName'] = $_FILES['uploadedFile']['name'];
}
$edit_selected = $_POST['templateName'];
$target = $_FILES['uploadedFile']['tmp_name'];

}


/* ADD or EDIT FILES CONTENTS from PLAIN INPUT*/
if ($_POST['Submit']=='Add File' || $_POST['Submit']=='Add New File' || $_POST['Submit']=='Save File') {

$in = in_array($_POST['templateName'], $files);

if ($_POST['Submit']=='Add File' || $_POST['Submit']=='Add New File') {
	echo "<p>Adding...";
} else {
	echo "<p>Saving...";
}

$valid = validateName($_POST['templateName']);

if ((($_POST['Submit']=='Add File' && !$in) || 
	($_POST['Submit']=='Add New File' && !$in) ||
	($_POST['Submit']=='Save File' && $in)) &&
	($_POST['templateName']!='') &&
	$valid	){
	$all_correct = true;
} else $all_correct = false;

if ($all_correct) {
$fp = fopen($templates_path . $_POST['templateName'], "w");
if ($fp) {
	fwrite($fp, $_POST['plain_text']);
	fclose($fp);
	echo "...Done</p>";
} else {
 $all_correct = false;
}

}
if (!$all_correct) {
	echo "</p><p class=\"error-message\">Error: ";
	if (!$valid) {
		echo "File name contains at least 1 illegal character";
	}else if ($_POST['templateName'] == ''){
		echo "Name of Template must be filled in.";
	} else if ($_POST['Submit']=='Add File' || $_POST['Submit']=='Add New File') {
	 echo "Unable to add file (\"" . $_POST['templateName'] . "\"); file already exists.";
	} else if ($_POST['Submit']=='Save File') {
	 echo "Unable to save file (\"" . $_POST['templateName'] . "\"); file does not exist.";
	} else  if (!$fp) {
		echo "Unable to action; please try again.";
	}
	echo "</p>\n";
	if ($_POST['Submit']=='Add New File' || $_POST['Submit']=='Save File') {
		$edit_selected = $edit_selected = $_POST['templateName'];
	}
	$error_exists = true;
	
}

}


/* DELETE FILES*/
else if ($_POST['DeleteSelected']=='Delete Selected') {
echo "<p>Deleting...";
while (list($key,$value) = each($_POST)) {
	if (substr($key,0,7)=='delete_') {
	       	$output = shell_exec('rm "' . $templates_path . $files[substr($key,7)] . '"');
	}
}
echo "...Done</p>\n";
}




/* Generate Reports */
if ($_POST["Gen"]=="Generate Selected") {
echo "<p>Generating...</p>";
while (list($key,$value) = each($_POST)) {
	if (substr($key,0,7)=='delete_') {
		$temp = $files[substr($key,7)];
		shell_exec('touch "' . $templates_path . $temp . '"');
		if (substr($temp, count($temp)-5)===".tex") {
			$temp = substr($temp, 0, count($temp)-4) . "pdf";
//echo "<pre>" . $temp . "</pre>";	
		}
		$reports = $reports ."/var/www/output/". addcslashes($temp,' ') . " ";
	}
}
//	$outpiut = shell_exec('make -C /home/ubuntu/drd/its-a-profs-life -f /home/ubuntu/drd/its-a-profs-life/Makefile all 2>&1');
	 $output = shell_exec('make -C "/home/ubuntu/drd/its-a-profs-life" -f "/home/ubuntu/drd/its-a-profs-life/Makefile" "OUTPUTS='.$reports.'" 2>&1');
//	$output = shell_exec('make -C "/home/ubuntu/drd/its-a-profs-life" -f "/home/ubuntu/drd/its-a-profs-life/Makefile" "OUTPUTS=/var/www/output/latextest.pdf" 2>&1');
	echo "<div class=\"output\">\n";
	echo "<h3>Generate Output</h3>\n";
//echo "<p>$reports</p>";
	echo "<pre>$output</pre>\n"; //Collects output from script
	echo "</div>\n";
	if (strstr($output, "Error ")) {
		echo "<p class=\"error-message\">Error?: 'Error' has been detected in the output. Please review the generated document(s) or try again.</p>";
	} else	{
		echo "<p>...Done</p>\n";
	}
}
else if ($_POST["Gen"]=="Unpublish") {
	shell_exec('make -C /home/ubuntu/drd/its-a-profs-life -f /home/ubuntu/drd/its-a-profs-life/Makefile unpublish 2>&1');
	shell_exec('make -C /home/ubuntu/drd/its-a-profs-life -f /home/ubuntu/drd/its-a-profs-life/Makefile clean 2>&1');
}


echo "<form ";
if ($_GET['input']=='file') {
	echo "enctype='multipart/form-data' ";
}
echo " action='$editTemplate_link?input=" . $_GET['input'] . "' method='post'>\n";


/* Print sub navigation */
echo "<div class='sub-navigation'>";

echo "<input name='Switch'";
if ($_GET['input'] != 'file') {
	echo " class='selected'";
}
echo " type='Submit' value='Form Input' />\n";

if ($edit_selected=='' && !($_GET['input']=='' && $error_exists)) {
echo "<input name='Switch'";
if ($_GET['input'] == 'file') {
	echo " class='selected'";
}
echo " type='Submit' value='File Input' />\n";
} 
echo "<input name='Switch' type='Submit' value='Cancel' />\n";

echo "</div>";


if ($_GET['input']=='file') {

/* INPUT TABLE: File Input */
echo "<table class='file-input'>\n";
echo "<tr><td>Name of Template (include extension)</td>\n";
echo "<td><input type='text' name='templateName' ";
if ($error_exists) {
	echo "value='" . $_POST['templateName'] . "' ";
}
echo "/></td></tr>\n";
echo "<tr><td>Choose a file to upload:</td>\n";
echo "<td><input name='uploadedFile' type='file' /></td></tr>\n";
echo "</table>\n";
echo "<p>If the Name of Template is blank, the template file will be saved with its original name. File names can only include letter (a-z), numbers, underscores, dashes, or periods.</p>\n";
echo "<p><input type='Submit' name='Submit' value='Upload File' /></p>";



} else {



/* INPUT TABLE: Plain Text Input*/
echo "<table class='plain-input'>\n";
echo "<tr><td>Name of Template (include extension)</td>\n";
echo "<td class='align-right'><input type='text' name='templateName' ";
if ($edit_selected != '') {
	echo 'value="' . $edit_selected . '" ';
} else if ($error_exists) {
	echo 'value="' . $_POST['templateName'] . '" ';
}
echo "/></td></tr>\n";
echo "<tr><td colspan='2'><br /><textarea name='plain_text' rows='10' cols='60'>";
if ($error_exists) {
	echo $_POST['plain_text'];
} else if ($edit_selected != '') {
	$output = shell_exec('cat "' . $target . '"');
	echo $output;
}
echo "</textarea></td></tr>\n";
echo "</table>\n";
echo "<p>The Name of Template must be filled. File names can only include letter (a-z), numbers, underscores, dashes, or periods. </p>\n";
if ($edit_selected != '' && $_POST['Switch']!='Form Input') {
	echo "<p><input type='Submit' name='Submit' value='Save File' /> ";
	echo "<input type='Submit' name='Submit' value='Add New File' /></p>";
} else {
	echo "<p><input type='Submit' name='Submit' value='Add File' /></p>";
}


} /* end else for Plain Text input*/
echo "</form>\n";



?>

<a href="/output">Location where files should be sent to</a> (Should be private)

<?php




/* DISPLAY TABLE of available templates */
$output = shell_exec('ls -i1 "' . $templates_path. '"');
unset($files);
unset($plain);
$plain = preg_split("/[\n]+/", $output, -1, PREG_SPLIT_NO_EMPTY);
foreach ($plain as &$value){
        $value = trim($value);
        $files[substr($value, 0, strpos($value, " "))] = substr(strstr($value," "),1);
}

$output = shell_exec('ls -l --time-style=long-iso "' . $templates_path . '" | sed "s/ * / /g" | cut -d " " -f 6,7');
//echo "<pre>" . $output . "</pre>";
$plain = preg_split("/[\n]+/", $output, -1, PREG_SPLIT_NO_EMPTY);

echo "<form action='$editTemplate_link?input=" . $_GET['input'] . "' method='POST'>\n";
echo "<div class=\"scrollableContainer\" style=\"width:" . (99 + (149*2)) . "px\">\n";
echo "<div class=\"scrollingArea\">\n";
echo "<table class=\"display scrollable\">\n";
echo "<thead>\n";
echo "<tr><th class=\"check-box\"><div></div></th>";
echo "<th class=\"edit-submit\"><div></div></th>";
echo "<th class=\"field\"><div>Name</div></th>";
echo "<th class=\"field\"><div>Date Modified</div></th></tr>\n";
echo "</thead><tbody>\n";
$i=0;
while (list($key, $value) = each ($files)) {
        echo "<tr>\n";
	/* Check box to select value (for Delete and Generate) */
        echo "<td class=\"check-box\"><div><input type='checkbox' ";
	if ($_POST['Selected']=='Select All') {
		echo "checked='yes' ";
	}
	echo "name='delete_" . $key . "' value='Yes' /></div></td>\n";
	/* Submit button to Edit File */
        echo "<td class=\"edit-submit\"><div><input type='submit' name='edit_" . $key . "' value='Edit' /></div></td>\n";
	echo "<td class=\"field\"><div>" . $value . "</div></td>";
	echo "<td class=\"field\"><div>" . $plain[$i] . "</div></td>";   
        echo "</tr>\n";
$i++;
}
echo "</tbody>\n";
echo "</table>\n";
echo "</div></div>\n"; /* Close divs for scrolling */
echo "<p><input type='submit' name='Selected' value='Select All' />".
	"<input type='submit' name='DeleteSelected' value='Delete Selected' />\n";
echo "<INPUT TYPE = 'Submit' Name = 'Gen' VALUE = 'Generate Selected' />\n";
echo "<INPUT TYPE = 'Submit' Name = 'Gen' VALUE = 'Unpublish' /></p>\n";
echo "</form>\n";

require('footer.inc.php');

?>

